package com.crm.controller;

import com.crm.pojo.User;
import com.crm.service.UserService;
import com.crm.util.ResultDto;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;


@RestController
public class LoginController {
    @Autowired
    private UserService userService;
    @PostMapping(value = "/login.do")
    public ResultDto login(String telephone,
                           String password,
                           @RequestParam(value = "isRememberMe",defaultValue = "0") Integer isRememberMe,
                           HttpServletRequest request){
        Subject subject=SecurityUtils.getSubject();
        UsernamePasswordToken token=new UsernamePasswordToken(telephone,password);
        /*
        if(isRememberMe==1){
            token.setRememberMe(true);//如果设置参数为true，表示实现记住我的功能
        }*/
        try {
            subject.login(token);
            User user=this.userService.findUserByTel(telephone);
            //获取Session对象
            Session session=subject.getSession();
            session.setAttribute("USER_SESSION",user);
            return ResultDto.LOGIN_SUCCESS;
        } catch (AuthenticationException e) {
            e.printStackTrace();
            request.setAttribute("error","用户名或者密码有误");
            return ResultDto.LOGIN_ERROR_PWD;
        }
    }
}
